package com.akl.ssmspringboot.controller;

import com.akl.ssmspringboot.entity.User;
import com.akl.ssmspringboot.service.UserService;
import com.akl.ssmspringboot.utils.PageResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName:
 * @Author: Guoxy
 * @Date: Created in 0:32 2018/11/7
 * @Version:1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public ModelAndView findList(Integer currPage, Integer pageSize, User user) {
        ModelAndView mv = new ModelAndView("user/list");
        currPage = currPage == null ? 1 : currPage;
        pageSize = pageSize == null ? 5 : pageSize;
        PageResult<User> page = userService.pageFind(currPage, pageSize, user);
        int totalCount = page.getTotalCount();
        int pages = page.getTotalCount() / pageSize;
        if (totalCount % pageSize != 0) {
            pages++;
        }
        List<User> list = page.getList();
        mv.addObject("pages", pages);
        mv.addObject("page", page);
        mv.addObject("user", user);
        mv.addObject("listVar", list);
        return mv;
    }

    @RequestMapping("/toAdd")
    public ModelAndView toAddUser() {
        return new ModelAndView("user/add");
    }

    @RequestMapping("/addUser")
    public String addUser(@Valid User user, BindingResult bindingResult) {
        int userId = userService.addUser(user);
        ModelAndView mv = new ModelAndView("user/list");
        mv.addObject("userId", userId);
        if (bindingResult.hasErrors()) {
            StringBuffer sb = new StringBuffer();
            for (ObjectError objectError : bindingResult.getAllErrors()) {
                sb.append(((FieldError) objectError).getField() + " : ").append(objectError.getDefaultMessage());
            }
            return sb.toString();
        }
        return "redirect:../user/list";
    }

    @RequestMapping("/delUser/{userId}")
    public String delUser(@PathVariable Integer userId) {
        userService.delUser(userId);
        return "redirect:../list";
    }

    @RequestMapping("/toUpdate/{userId}")
    public ModelAndView toUpdate(@PathVariable Integer userId) {

        User user = userService.findUserById(userId);
        ModelAndView mv = new ModelAndView("user/update");
        mv.addObject("user", user);
        return mv;
    }

    @RequestMapping("/updateUser")
    public String updateUser(User user) {
        userService.updateUser(user);
        return "redirect:./list";
    }

    @RequestMapping("/checkUsername")
    @ResponseBody
    public String checkUsername(String username) {
        boolean result = userService.checkUsername(username);
        Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }

    @RequestMapping("/checkUptUsername")
    @ResponseBody
    public String checkUptUsername(Integer userId, String username) {
        boolean result = userService.checkUptUsername(userId, username);
        Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }

}
